package com.isoft.c2team3service2.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.isoft.c2team3service2.dto.CommentDTO;
import com.isoft.c2team3service2.entity.Comment;
import com.isoft.c2team3service2.entity.Person;
import com.isoft.c2team3service2.entity.Post;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.mapper.CommentMapper;
import com.isoft.c2team3service2.mapper.PersonMapper;
import com.isoft.c2team3service2.mapper.PostMapper;
import com.isoft.c2team3service2.service.CommentService;
import com.isoft.c2team3service2.service.PostService;
import com.isoft.c2team3service2.service.SensitiveWordService;
import com.isoft.c2team3service2.util.UserHolder;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static com.isoft.c2team3service2.util.RedisConstants.POST_COMMENT_LIST;
import static com.isoft.c2team3service2.util.RedisConstants.USER_LOGIN_KEY;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private PostService postService;
    @Resource
    private SensitiveWordService sensitiveWordService;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private PostMapper postMapper;
    private static final Logger log = LoggerFactory.getLogger(CommentServiceImpl.class);

    // 关键修改1：按帖子ID查询评论（原按articleId查）
    @Override
    public List<CommentDTO> getCommentsByPostId(Integer postId) {
        List<CommentDTO> comments = commentMapper.getCommentsByPostId(postId);

        // 用过滤后内容覆盖原始内容（避免敏感词泄露）
        comments.forEach(comment -> {
            comment.setContent(comment.getFilteredContent());
        });

        try {
            String key = POST_COMMENT_LIST + ":" + postId;
            String jsonValue = objectMapper.writeValueAsString(comments);
            stringRedisTemplate.opsForValue().set(key, jsonValue);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return comments;
    }

    // 关键修改2：添加评论时关联正确的帖子ID（删除getNextArticleId调用）
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addComment(Comment comment) {
        // 1. 校验帖子是否存在（私密帖子不允许评论）
        Integer postId = comment.getPostId(); // 直接获取前端传入的帖子ID
        Post post = postService.findById(postId);
        if (post == null) {
            log.error("评论失败：帖子{}不存在或无权限查看", postId);
            return null;
        }
        if (post.getIsPrivate() == 1) {
            log.error("评论失败：帖子{}为私密帖子，不允许评论", postId);
            return null;
        }

        UserDTO user = UserHolder.getUser();
        if (user == null) {
            log.error("评论失败：用户未登录");
            return null;
        }

        // 3. 设置评论的基础信息（关联正确的帖子ID）
        comment.setNickName(user.getNickName());
        comment.setUserId(user.getId());
        comment.setPostId(postId); // 关键：直接用传入的帖子ID，而非生成自增ID
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        comment.setStatus(1); // 默认正常状态（若需审核可设为0）
        comment.setContent(comment.getContent());

        // 2. 敏感词过滤
        String filteredContent = sensitiveWordService.filterText(comment.getContent());

        if (filteredContent.endsWith("（敏感词）")) {
            return 0;
        }else{
            // 4. 保存评论并更新帖子的评论数
            comment.setFilteredContent(filteredContent);
            List<String> roles = user.getRoles();
            String role = roles.get(0);
            if (role.equals("艺人")) {
                postMapper.updateState(postId);
            }
            boolean success = save(comment);
            if (success) {
                postService.lambdaUpdate()
                        .setSql("comment_count = comment_count + 1")
                        .eq(Post::getId, postId) // 关联帖子ID更新评论数
                        .update();
                return comment.getId(); // 返回新增评论的ID
            }
        }
        return null;
    }

    // 关键修改3：删除评论时同步更新帖子的评论数（关联postId）
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteComment(Integer commentId, Integer userId) {
        Comment comment = getById(commentId);
        if (comment == null || !comment.getUserId().equals(userId)) {
            return false; // 评论不存在或无权限删除
        }

        boolean success = removeById(commentId);
        if (success) {
            // 按评论关联的postId更新帖子评论数
            postService.lambdaUpdate()
                    .setSql("comment_count = comment_count - 1")
                    .eq(Post::getId, comment.getPostId())
                    .update();
        }
        return success;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateComment(Integer commentId, Comment updatedComment) {
        // 原有逻辑保留，仅需确保未涉及articleId（已改为postId，此处无影响）
        Comment originalComment = getById(commentId);
        if (originalComment == null)
        {
            return false;
        }
        UserDTO user = UserHolder.getUser();
        if (!originalComment.getUserId().equals(user.getId()))
        {
            return false;
        }
        // 敏感词过滤
        String rawContent = updatedComment.getContent();
        String filteredContent = sensitiveWordService.filterText(rawContent);

        if (filteredContent.endsWith("（敏感词）")) {
            return false;
        }else {
            // 更新评论内容
            boolean updateSuccess = lambdaUpdate()
                    .eq(Comment::getId, commentId)
                    .set(Comment::getContent, rawContent)
                    .set(Comment::getFilteredContent, filteredContent)
                    .set(Comment::getUpdateTime, LocalDateTime.now())
                    .update();

            // 若用户昵称变更，同步更新评论的nickName
            Person person = personMapper.selectById(user.getId());
            if (person != null && !person.getNickName().equals(originalComment.getNickName())) {
                lambdaUpdate()
                        .eq(Comment::getId, commentId)
                        .set(Comment::getNickName, person.getNickName())
                        .update();
            }
            return updateSuccess;
        }
    }
}